import 'dart:developer';

import 'package:flutter_demo/constants/http_response_code.dart';
import 'package:flutter_demo/ui/graphQL_test/model/http_response.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

///@date:  2024/1/18
///@author:  ZhangPing
///@description:QueryResult类方法扩展

extension QueryResultExtension<TParsed> on QueryResult {
  HttpBaseResponse<T>? getErrorResponse<T>() {
    if (hasException) {
      if (exception?.linkException != null) {
        var errorType = exception?.linkException?.runtimeType;
        var errorMessage =
            exception?.linkException?.originalException?.toString();
        var message = "$errorType:$errorMessage";
        log(message);
        return HttpBaseResponse(
            code: HttpResponseCode.graphQLLinkException, message: message);
      } else if (exception?.graphqlErrors != null) {
        var graphqlError = exception!.graphqlErrors!;
        var errorInfo = graphqlError
            .map((e) => "${e.path?.join(',')}:${e.message}")
            .join("\n");
        log(errorInfo);
        return HttpBaseResponse(
            code: HttpResponseCode.graphQLError, message: errorInfo);
      }
    }
    return null;
  }
}
